#!/usr/bin/python

import os
import sys
import glob
import Image

def compare(f1, f2, cname):
    try:
        i1 = Image.open(f1)
        i2 = Image.open(f2)
    except IOError:
        return 0.0
    i3 = Image.new("RGBA", (320, 240))

    w, h = i1.size

    if (w, h) != i2.size:
        return 0.0

    score, maxi = 0, 0
    for x in range(w):
        for y in range(h):
            if i1.getpixel((x, y)) == i2.getpixel((x, y)):
                score += 1
            maxi += 1
            i3.putpixel((x, y), tuple([max(a,b) - min(a,b) for a, b in zip(i1.getpixel((x, y))[:3], i2.getpixel((x, y))[:3])]) + (255, ))

    i3.save(cname)
    return float(score) / float(maxi)

def test():
    total = (0, 0, 0)
    for f in os.listdir("./"):
        if not os.path.isdir(f) or f[0] == ".":
            continue

        os.chdir(f)

        os.system("gcc -o test_real.o -DGL2x_REAL -g -c ../test.c")
        os.system("gcc -o test_gl2x.o -g -c ../test.c")
        os.system("gcc -o %s.o -g -c %s.c" % (f,f))
        os.system("gcc -o real -g test_real.o %s.o -lSDL -lgl2x_real -lGL -lIL" % (f, ))
        os.system("gcc -o gl2x -g test_gl2x.o %s.o -lSDL -lgl2x_pc -lIL" % (f, ))

        os.system("./real")
        os.system("./gl2x")

        name = open("name.txt", "r").readline()[:-1]

        for fname in glob.glob("real*.png"):
            num = int(fname.split(".")[0][4:])
            score = compare("gl2x%i.png" % (num, ), "real%i.png" % (num, ), "compare%i.png" % (num, ))

        os.chdir("../")

        if score > 0.9999:
            result = "P"
            total = (total[0] + 1, total[1], total[2] + score)
        else:
            result = "F"
            total = (total[0], total[1] + 1, total[2] + score)

        print f[:6] + " " * (6-len(f)) + ":", name[:20], " "*(20-len(name)), "|" + "="*int(score*30) + " "*(30-int(score*30))+"|", "%.3f%%" % (score*100, ), result
    print "Pass: %i, Fail: %i, Average Score: %.3f%%" % (total[0], total[1], (total[2]*100)/(total[0] + total[1]))

def clean():
    for f in os.listdir("./"):
        if not os.path.isdir(f) or f[0] == ".":
            continue

        os.chdir(f)

        try:
            os.unlink("gl2x")
        except OSError:
            pass
        try:
            os.unlink("real")
        except OSError:
            pass
        try:
            [os.unlink(x) for x in glob.glob("*.o")]
        except OSError:
            pass
        try:
            [os.unlink(x) for x in glob.glob("*.png")]
        except OSError:
            pass

        os.chdir("../")

if __name__ == "__main__":
    clean()
    if len(sys.argv) == 1 or sys.argv[1] != "clean":
        test()
